<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="接口编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入接口编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="接口名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入接口名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="接收方" prop="receive">
        <el-input
          v-model="queryParams.receive"
          placeholder="请输入接收方"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发送方" prop="sender">
        <el-input
          v-model="queryParams.sender"
          placeholder="请输入发送方"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="begintime">
        <el-date-picker
          v-model="queryParams.begintime"
          type="datetime"
          placeholder="开始时间>="
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endtime">
        <el-date-picker
          v-model="queryParams.endtime"
          type="datetime"
          placeholder="结束时间<="
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:siplog:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          :icon="Download"
          @click="handleExport"
          v-hasPermi="['system:siplog:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          @click="handleGoToItfdoc"
        >接口档案</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="siplogList" @selection-change="handleSelectionChange">
      <el-table-column type="selection"  align="center" />
      <el-table-column label="接口编码" align="center" prop="code" />
      <el-table-column label="接口名称" align="center" prop="name" />
      <el-table-column label="状态" align="center" prop="rxstatus" >
        <template #default="scope">
          <span>{{ scope.row.rxstatus }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据编码" align="center" prop="billcode"/>
      <el-table-column label="开始时间" align="center" >
        <template #default="scope">
          <span>{{ parseTime(scope.row.begintime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" >
        <template #default="scope">
          <span>{{ parseTime(scope.row.endtime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="接收方" align="center" prop="receive" />
      <el-table-column label="发送方" align="center" prop="sender" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" :icon="View" @click="handleView(scope.row)" v-hasPermi="['system:siplog:query']">查看</el-button>
          <el-button link type="primary" :icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:siplog:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-wrapper">
      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 日志详情对话框 -->
    <el-dialog title="日志详情" v-model="detailOpen" width="80%" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="接口编码">{{ detailForm.code }}</el-descriptions-item>
        <el-descriptions-item label="接口名称">{{ detailForm.name }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ detailForm.rxstatus }}</el-descriptions-item>
        <el-descriptions-item label="单据编码">{{ detailForm.billcode }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ parseTime(detailForm.begintime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ parseTime(detailForm.endtime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="接收方">{{ detailForm.receive }}</el-descriptions-item>
        <el-descriptions-item label="发送方">{{ detailForm.sender }}</el-descriptions-item>
      </el-descriptions>
      
      <el-divider content-position="left">数据内容</el-divider>
      <el-input
        v-model="detailForm.datas"
        type="textarea"
        :rows="8"
        readonly
        placeholder="数据内容"
      />
      
      <el-divider content-position="left">返回消息</el-divider>
      <el-input
        v-model="detailForm.msg"
        type="textarea"
        :rows="6"
        readonly
        placeholder="返回消息"
      />
      
      <el-divider content-position="left" v-if="detailForm.errorstack">错误堆栈</el-divider>
      <el-input
        v-model="detailForm.errorstack"
        type="textarea"
        :rows="6"
        readonly
        placeholder="错误堆栈"
        v-if="detailForm.errorstack"
      />
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Siplog">
import { listSiplog, getSiplog, delSiplog, exportSiplog } from "@/api/system/siplog";
import { getCurrentInstance, ref, reactive, toRefs } from 'vue';
import { Delete, Search, Refresh, Download, View } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const { proxy } = getCurrentInstance();
const router = useRouter();

const siplogList = ref([]);
const detailOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const tableKey = ref(0); // 用于强制重新渲染表格

const data = reactive({
  detailForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    code: null,
    name: null,
    receive: null,
    sender: null,
    begintime: null,
    endtime: null,
  }
});

const { queryParams, detailForm } = toRefs(data);

// 解析时间格式的函数
function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null;
  }
  if (!time) {
    return null;
  }
  
  // 如果是字符串，转换为Date对象
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
  let date;
  
  if (typeof time === 'object') {
    date = time;
  } else {
    // 处理字符串格式的时间
    // 支持多种时间格式
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      // 如果是时间戳
      date = new Date(parseInt(time));
    } else if (typeof time === 'string') {
      // 替换可能的非标准分隔符
      const formattedTime = time.replace(/-/g, '/').replace('T', ' ').split('.')[0];
      date = new Date(formattedTime);
    } else {
      date = new Date(time);
    }
  }

  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };

  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value];
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value;
    }
    return value || 0;
  });

  return time_str;
}

/** 查询系统集成平台日志列表 */
function getList() {
  loading.value = true;
  console.log('开始获取日志列表...');
  listSiplog(queryParams.value).then(response => {
    console.log('接收到的响应数据:', response);
    // 检查返回的数据结构并适配
    if (response.flag === 'Y' || response.flag === 'true') {
      // 处理后端返回的特殊数据结构
      if (response.data && response.data.rows !== undefined && response.data.total !== undefined) {
        console.log('处理后端返回的数据结构');
        siplogList.value = response.data.rows;
        total.value = response.data.total;
        console.log('设置到siplogList的值:', siplogList.value);
      } else {
        // 如果是标准格式
        siplogList.value = response.data || [];
        total.value = response.total || 0;
        console.log('使用标准数据格式');
      }
    } else {
      siplogList.value = [];
      total.value = 0;
      ElMessage.error(response.msg || '获取数据失败');
    }
    console.log('最终siplogList值:', siplogList.value);
    // 更新tableKey以强制重新渲染表格
    tableKey.value += 1;
    loading.value = false;
  }).catch(error => {
    console.log('获取日志列表失败:', error);
    loading.value = false;
    // ElMessage.error('获取数据失败: ' + (error || '未知错误'));
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  // 使用code和begintime的组合作为唯一标识，如果后端有唯一ID字段则应使用该字段
  ids.value = selection.map(item => item.code + '_' + item.begintime);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 查看按钮操作 */
function handleView(row) {
  // 由于后端可能没有提供单独的查看API或主键，暂时显示行数据
  // 如果后端有提供根据条件查询单条记录的API，可以在这里调用
  detailForm.value = row;
  detailOpen.value = true;
  
  // 如果需要调用后端API，需要有明确的标识符
  // const pkLog = row.pkLog || ids.value;  // 这个字段在当前后端数据中不存在
  // getSiplog(pkLog).then(response => {
  //   detailForm.value = response.data;
  //   detailOpen.value = true;
  // });
}

/** 删除按钮操作 */
function handleDelete(row) {
  // 这里需要后端支持按code和begintime删除，或者提供唯一标识符
  // 当前仅作为示例，可能需要后端API支持
  let _logIds = '';
  if (row && row.code) {
    _logIds = row.code + '_' + row.begintime;
  } else {
    _logIds = ids.value;
  }
  
  proxy.$modal.confirm('是否确认删除系统集成平台日志编号为"' + _logIds + '"的数据项？').then(function() {
    // 注意：这里需要后端API支持，当前API可能不支持这种方式删除
    // return delSiplog(_logIds);
    // 由于当前API可能不支持基于code+time的删除，暂时提示用户
    ElMessage.warning("删除功能需要后端API支持");
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/siplog/export', {
    ...queryParams.value
  }, `siplog_${new Date().getTime()}.xlsx`)
}

/** 跳转到接口档案页面 */
function handleGoToItfdoc() {
  router.push('/itfdoc');
}

getList();
</script>
